package com.buer.storage.utils;


import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * Created by Administrator on 2021/2/5.
 */
public class PdfMerge {
    /**
     * pdf合并
     * @param inputStreams 要合并的pdf的InputStream数组
     * @return 合并后的pdf的二进制内容
     */
    public static byte[] mergePdfFiles(List<InputStream> inputStreams) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //Document document = new Document();// 创建一个新的PDF
        //50*50
        Rectangle rectangle = new Rectangle(142.0F, 142.0F);
        Document document = new Document(rectangle);

        byte[] pdfs = new byte[0];
        try {
            PdfCopy copy = new PdfCopy(document, bos);
            document.open();
            for (InputStream is : inputStreams) {// 取出单个PDF的数据
                PdfReader reader = new PdfReader(DownLoadUtils.InputStream2byte(is));
                int pageTotal= reader.getNumberOfPages();
//                logger.info("pdf的页码数是 ==> {}",pageTotal);
                for (int pageNo=1;pageNo<=pageTotal;pageNo++){
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, pageNo);
                    copy.addPage(page);
                }
                reader.close();
            }
            document.close();
            pdfs = bos.toByteArray();
            bos.close();
            copy.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
        return pdfs;
    }

}
